﻿@inject IDataConfigService DataConfigService
@inject IConfigDataService ConfigDataService

<MudDialog DisableSidePadding="true">
    <DialogContent>
        <MudContainer Style="height: 450px; overflow-y: scroll">
            @EditContent()
        </MudContainer>
    </DialogContent>
    <DialogActions>
        <MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="SubmitHandle">保存</MudButton>
        <MudButton Variant="Variant.Filled" OnClick="CancelHandle">取消</MudButton>
    </DialogActions>
</MudDialog>

@code {
    private IList<ConfigFieldInfoResponseDto> _allFields = new List<ConfigFieldInfoResponseDto>();
    private ConfigDataEditRequestDto _editRequestDto = new();

    private MudForm _editRequestForm = new();

    private ConfigDataEditValidator? _editValidator;

    //private UserEditValidator _editValidator;

    [CascadingParameter]
    MudDialogInstance MudDialog { get; set; }

    [Parameter]
    public Guid? Key { get; set; }

    [Parameter]
    public string ConfigCode { get; set; }

    protected override async Task OnInitializedAsync()
    {
        var result = await DataConfigService.QueryDataConfigFields(ConfigCode, new ConfigFieldSearchRequestDto());
        if (result != null && result.Data != null)
        {
            _allFields = result.Data;

            _editValidator = new ConfigDataEditValidator(_allFields);
        }

        await base.OnInitializedAsync();
    }

    void CancelHandle()
    {
        MudDialog.Cancel();
    }

    async Task SubmitHandle()
    {
        await _editRequestForm.Validate();

        if (Key != null)
        {
    // var result = await DataServerService.UpdateDatabase(Key.Value, _editRequestDto);
    //
    // if (result.Succeeded && MudDialog != null)
    // {
    //     MudDialog.Close(DialogResult.Ok(true));
    // }
        }
        else
        {
            IDictionary<string, object> valuePairs = new Dictionary<string, object>();
            valuePairs["ConfigCode"] = ConfigCode;
            foreach (var item in _allFields)
            {
                var name = item.FieldCode;
                var value = typeof(ConfigDataEditRequestDto).GetProperty(item.ValueColumnMap)?
                    .GetValue(_editRequestDto);
                if (!valuePairs.ContainsKey(name))
                {
                    valuePairs.Add(name, value);
                }
            }

            var result = await ConfigDataService.CreateConfigData(valuePairs);

            if (result.Succeeded && MudDialog != null)
            {
                MudDialog.Close(DialogResult.Ok(true));
            }
        }
    }

    RenderFragment EditContent()
    {
        return
            @<MudForm @ref="_editRequestForm" Model="_editRequestDto" Validation="@(_editValidator?.ValidateValue)" ValidationDelay="0">
                <MudGrid>
                    @foreach (var field in _allFields)
                    {
                        if (!string.IsNullOrEmpty(field.ControlType))
                        {
                            if (field.ControlType.Equals("ControlTextBox"))
                            {
                                <MudItem xs="6">
                                    <MudTextField T="string" Value="@(typeof(ConfigDataEditRequestDto).GetProperty(field.ValueColumnMap)?.GetValue(_editRequestDto)?.ToString())"
                                                  ValueChanged="@(v => ValueChangedHandle(v, field.ValueColumnMap))"
                                                  For="ConvertStringProperty(field.ValueColumnMap)" Label="@field.FieldName">
                                    </MudTextField>
                                </MudItem>
                            }
                            else if (field.ControlType.Equals("ControlSelect"))
                            {
                                if (field.DataSourceTypeSelect?.Equals("valuePair") ?? false)
                                {
                                    <MudItem xs="6">
                                        <MudSelect T="string" Label="@field.FieldName"
                                                   Value="@(typeof(ConfigDataEditRequestDto).GetProperty(field.ValueColumnMap)?.GetValue(_editRequestDto)?.ToString())"
                                                   ValueChanged="@(v => ValueChangedHandle(v, field.ValueColumnMap))"
                                                   For="ConvertStringProperty(field.ValueColumnMap)"
                                                   Dense="true" AnchorOrigin="Origin.BottomCenter" Clearable>
                                            @foreach (var item in field.DataSourceStaticValueSelect)
                                            {
                                                <MudSelectItem Value="@item.Key">@item.Value</MudSelectItem>
                                            }
                                        </MudSelect>
                                    </MudItem>
                                }
                            }
                        }
                    }
                </MudGrid>
            </MudForm>
            ;
    }

    void ValueChangedHandle(string value, string valueColumnMap)
    {
        typeof(ConfigDataEditRequestDto).GetProperty(valueColumnMap)?.SetValue(_editRequestDto, value);
    }

    Expression<Func<string?>> ConvertStringProperty(string valueColumnMap)
    {
    //Expression<Func<string?>> expression = () => _editRequestDto.VarcharAttribute2;
        Expression<Func<string?>> expression = Expression.Lambda<Func<string?>>(
            Expression.Property(Expression.Field(Expression.Constant(this, typeof(ConfigDataEdit)), "_editRequestDto"), valueColumnMap), Array.Empty<ParameterExpression>());

        return expression;
    }

}